<template>
  <!--
    时间：2024年10月8日11点32分
    我们这样，把菜单选项抽成组件，地图放在App中
  -->
  <div class="app-box">
    <div id="map-box" class="map-box"></div>
    <!--    <div class="menu-box">-->
    <!--      <el-button>图层</el-button>-->
    <!--      <el-button type="primary">搜索</el-button>-->
    <!--    </div>-->
    <base-map-control
      @change-basemap="changeBasemap"
      @change-transparency="changeTransparency"
      @positioning-btn="positioningBtn"
      @add-visual-angle="addVisualAngle"
      @visual-angle-btn="visualAngleBtn"
      @location-item-btn="locationItemBtn"
      @location-search-btn="locationSearchBtn"
      :visual-angle-list="visualAngleList"
      :baseMapList="baseMapList3"
    />

    <current-latitude-and-longitude
      :latitude="latitude"
      :longitude="longitude"
      :altitude="altitude"
    />

    <el-button
      @click="drawPointer"
      style="position: absolute; top:0;left: 0;"
      :type="isDrawPointer?'primary':''"
    >绘制点
    </el-button>

    <el-button
      @click="drawPolyline"
      style="position: absolute; top:0;left: 70px;"
    >绘制折线
    </el-button>

    <el-button
      @click="drawPolygon"
      style="position: absolute; top:0;left: 170px;"
    >
      绘制面
    </el-button>

    <el-button
      @click="dTilesDialogFormVisible=true"
      style="position: absolute; top:0;left: 255px;"
    >加载3D Tiles
    </el-button>

    <el-button
      @click="measureDistanceBtn('line')"
      style="position: absolute; top:50px;left: -10px;"
    >
      距离测量
    </el-button>

    <!--    <el-button-->
    <!--      @click="measureDistanceBtn('polygon')"-->
    <!--      style="position: absolute; top:50px;left: 100px;"-->
    <!--    >-->
    <!--      面积测量-->
    <!--    </el-button>-->

    <el-button
      @click="clearAllShapes"
      style="position: absolute; top:50px;left: 100px;">
      清空距离测量
    </el-button>


    <!--    <el-button-->
    <!--      @click="getAllCesiumLayers"-->
    <!--      style="position: absolute; top: 50px;left: 100px;"-->
    <!--    >-->
    <!--      获取所有图层-->
    <!--    </el-button> -->
    <el-button
      @click="pointDialogFormVisible=true"
      style="position: absolute; top: 100px;left: -10px;"
    >
      添加点缓冲区
    </el-button>

    <el-button
      @click="pointLineDialogFormVisible=true"
      style="position: absolute; top: 100px;left: 120px;"
    >
      添加线缓冲区
    </el-button>

    <el-button
      @click="surfaceDialogFormVisible=true"
      style="position: absolute; top: 100px;left: 250px;"
    >
      添加面缓冲区
    </el-button>

    <el-button
      @click="clearBuffer"
      style="position: absolute; top: 100px;left: 380px;"
    >
      清空缓冲区
    </el-button>

    <el-button
      @click="terrainExcavationFun"
      style="position: absolute; top: 150px;left: -10px;"
      :type="isTerrainExcavation?'primary':''"
    >
      地形开挖
    </el-button>


    <!--  注意，这里我们需要通过属性去判断，或者再定义一个新的专门用于弹框显示的变量  -->
    <!--    <div class="popup-message-content" v-show="currentFeatureObject.expno">-->
    <!--      <ul class="popup-box"-->
    <!--          :style="{left:`${popupBoxPosition.x}px`,top:`${popupBoxPosition.y}px`}">-->
    <!--        <li>编号：{{ currentFeatureObject.expno }}</li>-->
    <!--        <li>部门：{{ currentFeatureObject.belong }}</li>-->
    <!--        <li>名称：{{ currentFeatureObject.prj_name }}</li>-->
    <!--      </ul>-->
    <!--    </div>-->

    <!--  动态加载3DTiles弹框  -->
    <el-dialog v-model="dTilesDialogFormVisible" title="动态加载3DTiles" width="500">
      <el-form :model="dTileForm">
        <el-form-item label="请输入在线地址">
          <el-input v-model="dTileForm.url" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dTilesDialogFormVisible=false">关闭</el-button>
          <el-button type="primary" @click="add3dTile">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--  点缓冲区弹框  -->
    <el-dialog v-model="pointDialogFormVisible" title="点缓冲区大小" width="500">
      <el-form :model="pointDialogForm">
        <el-form-item label="请输入缓冲区范围(单位: 米)">
          <el-input v-model="pointDialogForm.range" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pointDialogFormVisible = false">关闭</el-button>
          <el-button type="primary" @click="pointDialogFormSubmitBtn">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--  线缓冲区弹框  -->
    <el-dialog v-model="pointLineDialogFormVisible" title="线缓冲区大小" width="500">
      <el-form :model="pointLineDialogForm">
        <el-form-item label="请输入缓冲区范围(单位: 米)">
          <el-input v-model="pointLineDialogForm.range" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pointLineDialogFormVisible = false">关闭</el-button>
          <el-button type="primary" @click="addPolylineBuffer">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--  线缓冲区弹框  -->
    <el-dialog v-model="surfaceDialogFormVisible" title="面缓冲区大小" width="500">
      <el-form :model="surfaceDialogForm">
        <el-form-item label="请输入缓冲区范围(单位: 米)">
          <el-input v-model="surfaceDialogForm.range" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="surfaceDialogFormVisible = false">关闭</el-button>
          <el-button type="primary" @click="addPolygonBuffer">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>
<script setup>
import * as Cesium from "cesium";
import {onMounted, reactive, ref} from "vue";
import BaseMapControl from "./components/BaseMapControl.vue";
import {Cartesian3} from "cesium";
import CurrentLatitudeAndLongitude from "./components/CurrentLatitudeAndLongitude.vue";
import axios from "axios";
import proj4 from "proj4";
import Bubble from "./utils/Bubble.js";
import {baseMapListFindById} from "./utils/Recursion.js";
import {getCatesian3FromPX} from "./utils/PositionPicking.js";
import DrawPolylineUtils from "./utils/DrawPolyLine.js";
import DrawPolygon from "./utils/DrawPolygon.js";
import {MeasureDistance} from "./utils/MeasureUtil.js";
import {
  clearAllEntitiesList,
  initPointBuffer,
  initPolygonBuffer,
  initPolylineBuffer,
  updatePolygonBuffer,
  updatePolylineBuffer
} from "./utils/BufferAnalysis.js";
import initExcavationTool from "./utils/Excavation.js";
import TerrainClipPlan from "./utils/TerrainExcavationByBlog.js";
import {calDrawLines, clearAllShapesUtils} from "./utils/calDrawLines.js";
import TerrainCutting2 from "./utils/TerrainExcavationByBlog2.js";
import TerrainExcavation2 from "./utils/TerrainExcavation2.js";
import TerrainExcavation from "./utils/TerrainExcavationByExample.js";

const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwMzZhYjBmNy04MGU0LTRhYmUtYjZiNy0wYjYzNzBkNjdjZGQiLCJpZCI6MjE2OCwiaWF0IjoxNjY3MDM4MTQ5fQ.GNh4g9vd4Zikl-IDk7Ehr8GOe-APZqKgqA7dkBs3bTo";
//全局的viewer
let viewer;
//全局的addImageryProvider(添加图层后返回的参数,用于设置图层的透明度、亮度、对比度等等)
let addImageryProvider;
/** 图层的列表,用于保存图层和设置图层的透明度 */
const imageryProviderList = [];
/** 地图列表,这里必须要把她从子组件传过来,否则默认的透明度无法使用 */
let basemapArray = [];
/** 搜索列表,这里我们需要在全局中进行使用 */
let options = [];
/** 记录当前位置高亮的数组，用于在取消后恢复 */
const locationSelectEntityList = [];
//纬度
const latitude = ref(0);
//经度
const longitude = ref(0);
//高程
const altitude = ref(0);
/** 当前是否正在绘制点 */
const isDrawPointer = ref(false);
const isDrawPointerLine = ref(false);
const dialogFormVisible = ref(false);
const form = reactive({
  range: 30,
});

//点缓冲区弹框
const pointDialogFormVisible = ref(false);
//点缓冲区弹框表单
const pointDialogForm = reactive({
  range: 30,
});
//线缓冲区弹框
const pointLineDialogFormVisible = ref(false);
//点缓冲区弹框表单
const pointLineDialogForm = reactive({
  range: 30,
});
//面缓冲区弹框
const surfaceDialogFormVisible = ref(false);
//面缓冲区弹框表单
const surfaceDialogForm = reactive({
  range: 30,
});


/**
 * 底图列表
 * item结构说明
 *  {
 *     id: 1,
 *     title: "Bing底图（影像）",
 *     type: "bing",
 *     //透明度
 *     transparency: 100,
 *     //cesium图层对象
 *     imageryProvider:null
 *   },
 */

/**
 * @description 底图列表
 * 但是底图的列表是树形接口，怎么写？？？
 * 这里我们将数据结构全部重写，现在写的过于混乱了
 * id:item的唯一id
 * title:展示的名称
 * transparency: 透明度
 * imageryProvider: 图层对象
 * children:[]
 */
const baseMapList = ref([
  {
    id: 1,
    title: "Bing底图（影像）",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 2,
    title: "天地图（矢量）",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 3,
    title: "ArcGIS在线地图",
    type: "arcgis",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 4,
    title: "高德底图",
    type: "gaode",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 5,
    title: "天地图（影像）",
    type: "tianditu",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 6,
    title: "Bing底图（矢量）",
    type: "bing_shiliang",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 7,
    title: "株洲GeoServer地图",
    type: "zhuzhou",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 8,
    title: "江苏省矢量底图",
    type: "jiangsu",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 9,
    title: "江苏省中学底图",
    type: "jiangsu_zhongxue",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 10,
    title: "江苏省医院底图",
    type: "jiangsu_yiyuan",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
  {
    id: 11,
    title: "江苏省注记底图",
    type: "jiangsu_zhuji",
    //透明度
    transparency: 100,
    //cesium图层对象
    imageryProvider: null
  },
]);

//注意，这里不能立刻去赋值，
//而是在onMount中进行赋值
const baseMapList2 = ref();

/** 普通的数组 */
const baseMapList3 = ref();

/** 画线还是画面 */
const drawingMode = ref('');
/**
 * 当前要素对象
 * 这里我们暂时四个字段
 * expno
 * belong
 * prj_name
 */
const currentFeatureObject = ref({});
/** 弹框显示的位置， */
const popupBoxPosition = ref({
  x: 0,
  y: 0
});

/**
 * 视角列表
 * 这里我们写一下item的数据类型
 * {
 *   id,
 *   title,
 *   x,
 *   y,
 *   z,
 *   pitch,
 *   heading,
 *   imageUrl
 * }
 */
const visualAngleList = ref([]);

/** 是否正在使用地形开挖 */
const isTerrainExcavation = ref(false);
/** 3dTiles弹框是否显示 */
const dTilesDialogFormVisible = ref(false);
/**  3dTiles弹框表单 */
const dTileForm = reactive({
  url: ""
})

/** 全局的地图canvas对象 */
let publicCesiumHandler;


onMounted(async () => {
  Cesium.Ion.defaultAccessToken = token;
  //初始化地图
  viewer = new Cesium.Viewer('map-box', {
    animation: false,
    imageryProvider: false,
    fullscreenButton: false,
    geocoder: false,
    homeButton: false,
    infoBox: false,
    sceneModePicker: false,
    selectionIndicator: false,
    timeline: false,
    navigationHelpButton: false,
    scene3DOnly: true,
    orderIndependentTranslucency: false,
    contextOptions: {
      webgl: {
        alpha: true
      }
    }
  });
  //开启深度检测
  viewer.scene.globe.depthTestAgainstTerrain = true;
  /** 移除第一项 */
  viewer.imageryLayers.remove(viewer.imageryLayers.get(0));
  baseMapList3.value = [
    {
      id: '1-1',
      title: "Bing底图（影像）",
      //透明度
      transparency: 100,
      //cesium图层对象
      imageryProvider: addBingLayer(),
    },
    {
      id: '1-2',
      title: "Bing底图（矢量）",
      //透明度
      transparency: 100,
      //cesium图层对象
      imageryProvider: addBingLayerByShiLiang(),
    },
    {
      id: '2-1',
      title: "天地图（影像）",
      //透明度
      transparency: 100,
      //cesium图层对象
      imageryProvider: addTianDiTuLayerByYingXiang(),
    },
    {
      id: '2-2',
      title: "天地图（矢量）",
      //透明度
      transparency: 100,
      //cesium图层对象
      imageryProvider: addTianDiTuLayer(),
    },
    {
      id: '3',
      title: "ArcGIS",
      transparency: 100,
      imageryProvider: addArcGisLayer(),
    },
    {
      id: '4',
      title: "高德",
      transparency: 100,
      imageryProvider: addGaoDeLayer(),
    },
    {
      id: '5',
      title: "株洲底图",
      transparency: 100,
      imageryProvider: addZhuzhouWmsLayer(),
    },
    {
      id: '6',
      title: "江苏矢量底图",
      transparency: 100,
      imageryProvider: addJinagSuByShiLiangLayer(),
    },
    {
      id: '7',
      title: "江苏注记底图",
      transparency: 100,
      imageryProvider: addJinagSuByZhuJiLayer(),
    },
    {
      id: '8',
      title: "江苏中学",
      transparency: 100,
      imageryProvider: addJinagSuByZhongXueLayer(),
    },
    {
      id: '9',
      title: "江苏医院",
      transparency: 100,
      imageryProvider: addJinagSuByYiYuanLayer(),
    },
  ];
  //全部隐藏
  // baseMapList3.value.forEach((item, index) => {
  //   console.log(893, item.imageryProvider);
  //   console.log(894, item.imageryProvider instanceof Promise);
  //   if (item.imageryProvider instanceof Promise) {
  //     item.imageryProvider.then((result) => {
  //       result.show = false;
  //     }, (error) => {
  //       console.log(error);
  //     });
  //   } else {
  //     item.imageryProvider.show = false;
  //   }
  // });
  /** 注册事件 */
  publicCesiumHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  /** 注册鼠标移动事件 */
  publicCesiumHandler.setInputAction(function (movement) {
    const ellipsoid = viewer.scene.globe.ellipsoid;
    //捕获椭球体，将笛卡尔二维平面坐标转为椭球体的笛卡尔三维坐标，返回球体表面的点
    const cartesian = viewer.camera.pickEllipsoid(movement.endPosition, ellipsoid);
    if (cartesian) {
      //将笛卡尔三维坐标转为地图坐标（弧度）
      const cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
      //将地图坐标（弧度）转为十进制的度数
      const lat_String = Cesium.Math.toDegrees(cartographic.latitude).toFixed(4);
      const log_String = Cesium.Math.toDegrees(cartographic.longitude).toFixed(4);
      const alti_String = (viewer.camera.positionCartographic.height / 1000).toFixed(2);
      // longitude_show.innerHTML = log_String;
      // latitude_show.innerHTML = lat_String;
      // altitude_show.innerHTML = alti_String;
      latitude.value = lat_String;
      longitude.value = log_String;
      altitude.value = alti_String;
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  /** 注册cesium单击事件 */
  publicCesiumHandler.setInputAction(function (event) {
    // console.log(117, "单击事件");
    // console.log(118, event.position);
    //弹框的工具类
    let bubble = new Bubble({
      viewer: viewer
    });
    /** 加一个新需求，单击时，弹框一次只显示一个 */
    //本质就是清空
    //将数据清空
    currentFeatureObject.value = {
      expno: undefined,
      belong: undefined,
      prj_name: undefined,
    };
    //关闭弹框
    bubble.clearDiv();
    //清空entity高亮效果,(即换图片)
    locationSelectEntityList.forEach((item) => {
      item.billboard.image = "/src/assets/image/biao_ji.png";
    });
    /** ----------------------------------- */
      // 获取点击位置的对象
    let pickedObject = viewer.scene.pick(event.position);
    //判断是否点击到了 entity
    if (Cesium.defined(pickedObject) && pickedObject.id) {
      // console.log(163, pickedObject);
      //这里我们动态添加一个属性过去,
      //用于动态渲染
      //整理当前需要显示的数据
      //这里我们通过 pickedObject 来获取当前单击的entity对象
      // const currentEntities = viewer.entities.getById(pickedObject.id._id);
      const currentEntities = pickedObject.id;
      console.log(164, currentEntities);
      currentEntities.billboard.image = "/src/assets/image/biao_ji_select.png";
      //此时，就需要我们修改entity对象的样式属性了
      //添加进高亮组
      locationSelectEntityList.push(currentEntities);
      if (currentEntities.myself_data) {//此时表示为搜索的
        // console.log(169, currentEntities.myself_data.hotPointID);
        currentFeatureObject.value = {
          expno: currentEntities.myself_data.hotPointID,
          belong: currentEntities.myself_data.name,
          prj_name: currentEntities.myself_data.address,
        };
      } else {
        currentFeatureObject.value = {
          expno: pickedObject.id.properties._expno._value,
          belong: pickedObject.id.properties._belong._value,
          prj_name: pickedObject.id.properties._prj_name._value,
        };
      }
      currentEntities.text = `
        <ul class="popup-box-ul">
          <li style="margin: 5px 0;width: 100%;overflow: hidden;text-overflow: ellipsis;text-wrap: nowrap;">编号：${currentFeatureObject.value.expno}</li>
          <li style="margin: 5px 0;width: 100%;overflow: hidden;text-overflow: ellipsis;text-wrap: nowrap;">名称：${currentFeatureObject.value.belong}</li>
          <li style="margin: 5px 0;width: 100%;overflow: hidden;text-overflow: ellipsis;text-wrap: nowrap;">地址：${currentFeatureObject.value.prj_name}</li>
        </ul>
      `;
      bubble.addDynamicLabel(currentEntities);
      console.log(123, pickedObject.id.properties);
      popupBoxPosition.value = event.position;
    } else {//在这里执行清空操作
      //将数据清空
      currentFeatureObject.value = {
        expno: undefined,
        belong: undefined,
        prj_name: undefined,
      };
      //关闭弹框
      bubble.clearDiv();
      //清空entity高亮效果,(即换图片)
      locationSelectEntityList.forEach((item) => {
        item.billboard.image = "/src/assets/image/biao_ji.png";
      });
    }
    //设置弹框的位置,这里的弹框是绝对固定,并不是随着地图而移动的
    //所以,我们需要加入这个代码,但是这个代码,我们目前看不懂
    // viewer.scene.postRender.addEventListener(() => {
    //   const canvasHeight = viewer.scene.canvas.height;
    //   const windowPosition = new Cesium.Cartesian2();
    //   // console.log(173, event.position);
    //   const position = Cesium.Cartesian3.fromDegrees(event.position.x, event.position.y);
    //   console.log(175, position);
    //   Cesium.SceneTransforms.worldToWindowCoordinates(
    //     viewer.scene,
    //     position,
    //     windowPosition
    //   );
    //   // popupBoxPosition.value = {
    //   //   x: windowPosition.x,
    //   //   y: windowPosition.y + 220,
    //   // }
    //   // console.log(185, popupBoxPosition.value);
    //   // div.style.bottom = canvasHeight - windowPosition.y +220 + "px";
    //   // const elWidth = div.offsetWidth;
    //   // div.style.left = windowPosition.x - elWidth / 2 + "px";
    // })
    // viewer.scene.postRender.addEventListener(function() {
    //   updatePopup(event.position);
    // });
    console.log(145, currentFeatureObject.value);
    //通过指定的椭球或者地图对应的坐标系，将鼠标的二维坐标转换为对应椭球体三维坐标
    // const cartesian = viewer.camera.pickEllipsoid(event.position, ellipsoid);
    // //将笛卡尔坐标转换为地理坐标
    // const cartographic = ellipsoid.cartesianToCartographic(cartesian);
    // //将弧度转为度的十进制度表示
    // const longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
    // const latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
    // const point = longitudeString + ',' + latitudeString;
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  /** 更新弹框位置 */
  // function updatePopup(position) {
  //   viewer.scene.postRender.addEventListener(function () {
  //     const windowPosition = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene,position);
  //     console.log(187, windowPosition);
  //   });
  // }

  //坐标系转化
  Cesium.GeoJsonDataSource.crsNames['urn:ogc:def:crs:EPSG::4547'] =
    Cesium.GeoJsonDataSource.crsNames['EPSG:4547'] = coordinates => {
      const fromProjection = `PROJCS["CGCS2000 / 3-degree Gauss-Kruger CM 114E",GEOGCS["China Geodetic Coordinate System 2000",DATUM["China_2000",SPHEROID["CGCS2000",6378137,298.257222101,AUTHORITY["EPSG","1024"]],AUTHORITY["EPSG","1043"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4490"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",114],PARAMETER["scale_factor",1],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","4547"]]`

      const toProjection = `GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]`

      const x = coordinates[0]
      const y = coordinates[1]

      const newCoordinates = proj4(fromProjection, toProjection, [x, y])
      return Cesium.Cartesian3.fromDegrees(
        newCoordinates[0],
        newCoordinates[1],
        0
      )
    }
//加载点数据
  fetch("http://192.168.1.137:8080/geoserver/zz_map/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=zz_map%3AWSPoint&maxFeatures=50&outputFormat=application%2Fjson").then((response) => {
    return response.json();
  }).then((result) => {
    console.log(125, result);
    // Cesium.GeoJsonDataSource.load(result)
    Cesium.GeoJsonDataSource.load(result).then((dataSource) => {
      //加载数据源到viewer
      viewer.dataSources.add(dataSource);
      //我们还需要获取所有wfs加载的数据，进行其样式的修改
      const entityList = dataSource.entities.values;
      //此时，我们对wfs加载过来的entityList进行遍历，可以对其进行样式的设置等等操作
      // entityList
      entityList.forEach((entity) => {
        entity.billboard = new Cesium.BillboardGraphics({
          image: "/src/assets/image/biao_ji.png",
        });
      });
      // viewer.flyTo(dataSource, {
      //   duration: 1,
      //   orientation: {
      //     heading: Cesium.Math.toRadians(90.0),  // 方位角（水平旋转角度）
      //     pitch: Cesium.Math.toRadians(-45.0),   // 俯仰角（相机上下旋转）
      //     roll: 0.0                             // 滚动角（相机左右倾斜）
      //   },
      // });
    });
  });

  // drawLineAndPolygon();
  //初始化底图和数据
  // initData();
});

/**
 * @description 绘制点
 */
function drawPointer() {
  isDrawPointer.value = !isDrawPointer.value;
  console.log(538, isDrawPointer.value);
  //这个对象我们在cesium已经注册过了，所以不能再 new 了
  // publicCesiumHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  if (isDrawPointer.value) {
    //监听鼠标左键点击事件
    publicCesiumHandler.setInputAction(function (click) {
      // 获取点击位置的地理坐标
      const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
      if (cartesian) {
        // 将 Cartesian 坐标转为地理坐标（经纬度）
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        const longitude = Cesium.Math.toDegrees(cartographic.longitude); // 经度
        const latitude = Cesium.Math.toDegrees(cartographic.latitude);   // 纬度
        // 添加点到地图上
        viewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(longitude, latitude),
          point: {
            pixelSize: 10,
            color: Cesium.Color.RED,
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 2
          },
          label: {
            text: 'Point at (' + longitude.toFixed(4) + ', ' + latitude.toFixed(4) + ')',
            font: '14pt monospace',
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            outlineWidth: 2,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(0, -20)
          }
        });
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
    /**
     * 注意，这里的事件不可以再使用 Cesium.ScreenSpaceEventType.LEFT_CLICK
     * 因为我们再之前已经使用了 LEFT_CLICK，所以我们需要换一个事件
     */
  } else {
    publicCesiumHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN);
  }
}

/**
 * @description 绘制折线
 */
function drawPolyline() {
  isDrawPointerLine.value = !isDrawPointerLine.value;
  //创建工具类
  const drawPolylineUtils = new DrawPolylineUtils({
    viewer,
    Cesium,
    cesiumHandler: publicCesiumHandler
  });
  if (isDrawPointerLine.value) {
    drawPolylineUtils.startCreate();
    // console.log(690, drawPolylineUtils._entities_point);
  }
  // console.log(691 ,drawPolylineUtils.getData());
  // const positions = [];
  // let polyline;
  // publicCesiumHandler.setInputAction(function (click) {
  //   const cartesian = viewer.scene.pickPosition(click.position);
  //   if (Cesium.defined(cartesian)) {
  //     positions.push(cartesian);
  //     if (positions.length > 1) {
  //       if (!Cesium.defined(polyline)) {
  //         polyline = viewer.entities.add({
  //           polyline: {
  //             positions: positions,
  //             width: 5,
  //             material: Cesium.Color.RED
  //           }
  //         });
  //       } else {
  //         polyline.polyline.positions = positions;
  //       }
  //     }
  //   }
  // }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
  // //双击结束绘制
  // publicCesiumHandler.setInputAction(function () {
  //   // 停止绘制，可以进行其他处理
  //   publicCesiumHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN);
  //   publicCesiumHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
  // }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
}

/**
 * @description 绘制面
 */
function drawPolygon() {
  const drawPolygon = new DrawPolygon({
    viewer,
    Cesium,
    cesiumHandler: publicCesiumHandler
  });
  drawPolygon.startCreate();
  // const positions = [];
  // let polygon;
  // publicCesiumHandler.setInputAction(function (click) {
  //   const cartesian = viewer.scene.pickPosition(click.position);
  //   if (Cesium.defined(cartesian)) {
  //     positions.push(cartesian);
  //     if (positions.length >= 3) {
  //       if (!Cesium.defined(polygon)) {
  //         polygon = viewer.entities.add({
  //           polygon: {
  //             hierarchy: new Cesium.CallbackProperty(function () {
  //               return new Cesium.PolygonHierarchy(positions);
  //             }, false),
  //             material: Cesium.Color.BLUE.withAlpha(0.5)
  //           }
  //         });
  //       }
  //     }
  //   }
  // }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
  // // 在双击时停止绘制
  // publicCesiumHandler.setInputAction(function () {
  //   publicCesiumHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN);
  //   publicCesiumHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
  // }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
}

/**
 * @description 这里我们使用cesium中提供的案例
 * @param worldPosition
 */
function createPoint(worldPosition) {
  return viewer.entities.add({
    position: worldPosition,
    point: {
      color: Cesium.Color.WHITE,
      pixelSize: 5,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    },
  });
}

function drawShape(positionData) {
  let shape;
  if (drawingMode.value === "line") {
    shape = viewer.entities.add({
      polyline: {
        positions: positionData,
        clampToGround: true,
        width: 3,
      },
    });
  } else if (drawingMode.value === "polygon") {
    shape = viewer.entities.add({
      polygon: {
        hierarchy: positionData,
        material: new Cesium.ColorMaterialProperty(
          Cesium.Color.WHITE.withAlpha(0.7),
        ),
      },
    });
  }
  return shape;
}

/**
 * @description cesium提供的画线和画面的在线综合案例
 */
function drawLineAndPolygon() {
  viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
    Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
  );
  let activeShapePoints = [];
  let activeShape;
  let floatingPoint;
  const handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
  handler.setInputAction(function (event) {
    // We use `viewer.scene.globe.pick here instead of `viewer.camera.pickEllipsoid` so that
    // we get the correct point when mousing over terrain.
    const ray = viewer.camera.getPickRay(event.position);
    const earthPosition = viewer.scene.globe.pick(ray, viewer.scene);
    // `earthPosition` will be undefined if our mouse is not over the globe.
    if (Cesium.defined(earthPosition)) {
      if (activeShapePoints.length === 0) {
        floatingPoint = createPoint(earthPosition);
        activeShapePoints.push(earthPosition);
        const dynamicPositions = new Cesium.CallbackProperty(function () {
          if (drawingMode === "polygon") {
            return new Cesium.PolygonHierarchy(activeShapePoints);
          }
          return activeShapePoints;
        }, false);
        activeShape = drawShape(dynamicPositions);
      }
      activeShapePoints.push(earthPosition);
      createPoint(earthPosition);
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  handler.setInputAction(function (event) {
    if (Cesium.defined(floatingPoint)) {
      const ray = viewer.camera.getPickRay(event.endPosition);
      const newPosition = viewer.scene.globe.pick(ray, viewer.scene);
      if (Cesium.defined(newPosition)) {
        floatingPoint.position.setValue(newPosition);
        activeShapePoints.pop();
        activeShapePoints.push(newPosition);
      }
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  function terminateShape() {
    activeShapePoints.pop();
    drawShape(activeShapePoints);
    viewer.entities.remove(floatingPoint);
    viewer.entities.remove(activeShape);
    floatingPoint = undefined;
    activeShape = undefined;
    activeShapePoints = [];
  }

  handler.setInputAction(function (event) {
    terminateShape();
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

// Zoom in to an area with mountains
  viewer.camera.lookAt(
    Cesium.Cartesian3.fromDegrees(-122.2058, 46.1955, 1000.0),
    new Cesium.Cartesian3(5000.0, 5000.0, 5000.0),
  );
  viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}

/**
 * @description 加载3DTiles方法
 */
async function add3dTile() {
  //开启地形检测
  viewer.scene.globe.depthTestAgainstTerrain = true;
  // 3D Tiles 服务的 URL
  // const tileset = await Cesium.Cesium3DTileset.fromUrl(
  //   "/src/assets/3d_tiles/tileset.json",
  // );
  //http://resource.dvgis.cn/data/3dtiles/dayanta/tileset.json //大雁塔
  //https://bucket-yufei.oss-cn-beijing.aliyuncs.com/01-project/04_wangxu_guation/tileset.json //大雁塔
  //http://www.njyskgis.com/mapdata/3dtiles/max-ytlhz/tileset.json //油管
  if (dTileForm.url !== "") {
    const tileset = await Cesium.Cesium3DTileset.fromUrl(
      dTileForm.url,
    );
    viewer.scene.primitives.add(tileset);
    viewer.scene.globe.depthTestAgainstTerrain = true;
    viewer.zoomTo(
      tileset,
      new Cesium.HeadingPitchRange(0.0, -0.5, tileset.boundingSphere.radius * 2.0),
    );
  }
  // const tileset = new Cesium.Cesium3DTileset({
  //   // url: '../public/SampleData/models/CesiumAir/Cesium_Air.glb' // 替换为你的3D Tiles服务URL
  //   url: '../public/SampleData/models/CesiumAir/Cesium_Air.glb' // 替换为你的3D Tiles服务URL
  // });
  //定位过去
  // viewer.zoomTo(tileset);
}

/**
 * @description 测量距离单击按钮
 * @param type
 */
function measureDistanceBtn(type) {
  // const measureDistance = new MeasureDistance(viewer, Cesium, publicCesiumHandler);
  // measureDistance.start();
  calDrawLines(viewer, type);
}

/**
 * @description 清除所有点线面
 */
function clearAllShapes() {
  clearAllShapesUtils(viewer);
}


/**
 * @description 初始化数据方法
 * 在这里，我们还需要对所有底图进行加载
 * 然后在切换时控制显隐
 *
 */
function initData(basemapList) {
  basemapArray = basemapList;
  // baseMapList.value.forEach((value, index)=>{
  //
  // })
  //加载全部底图
  baseMapList.value[0].imageryProvider = addBingLayer();
  baseMapList.value[1].imageryProvider = addTianDiTuLayer();
  addArcGisLayer().then((result) => {
    baseMapList.value[2].imageryProvider = result;
  });
  baseMapList.value[3].imageryProvider = addGaoDeLayer();
  baseMapList.value[4].imageryProvider = addTianDiTuLayerByYingXiang();
  addBingLayerByShiLiang().then((result) => {
    baseMapList.value[5].imageryProvider = result
  });
  baseMapList.value[6].imageryProvider = addZhuzhouWmsLayer();
  // basemapArray.forEach((item)=>{
  //   // item.imageryProvider=
  // });
  // baseMapList.value[7].imageryProvider =
  // baseMapList.value[8].imageryProvider =
  addJinagSuByShiLiangLayer();
  addJinagSuByZhongXueLayer();
  addJinagSuByYiYuanLayer();
  addJinagSuByZhuJiLayer();
}

/**
 * @description 地名搜索完毕后，搜索的的单击事件，用于定位
 * @param item 数据对象,需要加载到弹框中
 */
function locationItemBtn(item) {
  //整理经纬度数据
  const logAndLatList = item.lonlat.split(',')
  const lon = parseFloat(logAndLatList[0]);
  const lat = parseFloat(logAndLatList[1]);
  currentFeatureObject.value = {
    expno: item.hotPointID,
    belong: item.name,
    prj_name: item.address
  }
  //跳转
  viewer.camera.flyTo({
    destination: Cartesian3.fromDegrees(lon, lat, 300),
    duration: 1,
    orientation: {
      // heading: Cesium.Math.toRadians(90.0),  // 方位角（水平旋转角度）
      // pitch: Cesium.Math.toRadians(-45.0),   // 俯仰角（相机上下旋转）
      roll: 0.0                             // 滚动角（相机左右倾斜）
    },
  });
}

/**
 * @description 获取所有图层
 */
function getAllCesiumLayers() {
  console.log(919, viewer.imageryLayers);
}

/**
 * @description 搜索按钮的方法
 * @param optionsList 搜索的列表，我们需要进行遍历，然后创建要素，并加入到地图中去
 */
function locationSearchBtn(optionsList) {
  console.log(132, optionsList);
  options = optionsList;
  //获取后，我们开始遍历，并创建要素
  optionsList.forEach((item, index) => {
    console.log(275, item);
    //先整理数据
    const logAndLatList = item.lonlat.split(',')
    const log = parseFloat(logAndLatList[0]);
    const lat = parseFloat(logAndLatList[1]);
    //创建新要素
    const newEntity = new Cesium.Entity({
      //这里我们设置一个固定的id
      //通过这个id,遍历optionsList,找到对应的数据
      id: item.hotPointID,
      position: Cesium.Cartesian3.fromDegrees(log, lat, 10),
      label: {
        text: (index + 1) + "",
        font: "15"
      },
      //这里我们使用广告牌,然后添加一个图片
      billboard: {
        image: "src/assets/image/biao_ji.png"
        // text: (index + 1) + "",
        // fillColor: Cesium.Color.fromCssColorString('#000'),
        // font: "15"
      },
      // point: {
      //   // 点的大小（像素）
      //   pixelSize: 20,
      //   // 点位颜色，fromCssColorString 可以直接使用CSS颜色
      //   color: Cesium.Color.fromCssColorString('#ee0000'),
      //   // 边框颜色
      //   outlineColor: Cesium.Color.fromCssColorString('#fff'),
      //   // 边框宽度(像素)
      //   outlineWidth: 5,
      //   // 显示在距相机的距离处的属性，多少区间内是可以显示的
      //   // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 1500),
      //   // 是否显示
      //   show: true
      // },
    });
    //自定义动态属性，添加到entity中，看看是否能够获取
    newEntity.myself_data = item;
    //添加要素
    viewer.entities.add(newEntity);
  });
}


/**
 * @description 切换底图的方法
 * @param currentIndexList 已经存在的下标列表
 * @param currentBasemapItem 当前选中图层列表,用于图层置顶
 */
function changeBasemap(currentIndexList, currentBasemapItem) {
  //全部隐藏
  baseMapList3.value.forEach((item, index) => {
    if (item.imageryProvider instanceof Promise) {
      item.imageryProvider.then((result) => {
        result.show = false;
      }, (error) => {
        console.log(error);
      });
    } else {
      item.imageryProvider.show = false;
    }
  });

  if (currentIndexList.length) {
    //开始显示
    currentIndexList.forEach((item, index) => {
      const currentIndex = baseMapList3.value.findIndex((item2) => {
        return item2.id === item.value;
      });
      if (currentIndex !== -1) {
        console.log(867, '当前显示的', baseMapList3.value[currentIndex]);
        if (baseMapList3.value[currentIndex].imageryProvider instanceof Promise) {
          baseMapList3.value[currentIndex].imageryProvider.then((result) => {
            result.show = true;
          }, (error) => {
            console.log(error);
          });
        } else {
          baseMapList3.value[currentIndex].imageryProvider.show = true;
        }
      }
    });
    //显示完毕后,将刚刚加载的图层置顶
    // const currentIndex = baseMapList3.value.findIndex((item) => {
    //   return item.id === currentBasemapItem.value;
    // });
    // if (currentIndex !== -1) {
    //   if (baseMapList3.value[currentIndex].imageryProvider instanceof Promise) {
    //     baseMapList3.value[currentIndex].imageryProvider.then((result) => {
    //       // result.raiseToTop()
    //       console.log(1030, result);
    //       viewer.imageryLayers.raiseToTop(result);
    //     }, (error) => {
    //       console.log(error);
    //     });
    //   } else {
    //     viewer.imageryLayers.raiseToTop(baseMapList3.value[currentIndex].imageryProvider);
    //   }
    // }
  } else {
    //全部隐藏
    baseMapList3.value.forEach((item, index) => {
      if (item.imageryProvider instanceof Promise) {
        item.imageryProvider.then((result) => {
          result.show = false;
        }, (error) => {
          console.log(error);
        });
      } else {
        item.imageryProvider.show = false;
      }
    });
  }
}

/**
 * @description 透明度的切换
 * @param currentValue 透明度值
 * @param index 当前改变的下标
 */
function changeTransparency(currentValue, index) {
  const currentImageryProvider = baseMapList3.value[index].imageryProvider;
  console.log(1100, currentImageryProvider);
  if (currentImageryProvider instanceof Promise) {
    currentImageryProvider.then((result) => {
      console.log(1065, currentValue / 100);
      result.alpha = currentValue / 100;
    }, (error) => {
      console.log(error);
    });
  } else {
    currentImageryProvider.imageryProvider.alpha = currentValue / 100;
  }
}

/**
 * @description 固定定位操作
 * @param positionId 定位的类型，1表示全球，2表示中国，3表示株洲
 */
function positioningBtn(positionId) {
  switch (positionId) {
    case 1:
      viewer.camera.flyTo({
        destination: Cartesian3.fromDegrees(0, 0, 10000000.0),
        duration: 1
      });
      break;
    case 2:
      viewer.camera.flyTo({
        destination: Cartesian3.fromDegrees(116.435314, 40.960521, 10000000.0),
        duration: 1
      });
      break;
    case 3://加载wms地图服务株洲数据
      // viewer.camera.flyTo({
      //   destination: Cartesian3.fromDegrees(116.435314, 40.960521, 10000000.0),
      //   duration: 1
      // });

      break;
    default:
      console.log(77, "定位类型不存在，请检查 positionId");
      break;
  }
}

/**
 * @description 添加视角操作
 * 其实视角列表的本质就是添加经纬度和高程等信息，保存后再跳转。
 */
function addVisualAngle() {
  // 获取场景的 Canvas 元素
  const canvas = viewer.scene.canvas;
  // 将 canvas 转换为图片的 Data URL
  const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
  ;
  console.log(175, image);

  //获取当前视角的pitch
  const pitch = viewer.camera.pitch;
  //获取当前视角的heading
  const heading = viewer.camera.heading;
  //获取当前视角的posotion（位置）
  const position = viewer.camera.position;
  const x = position.x;
  const y = position.y;
  const z = position.z;
  const visualAngleObject = {
    id: visualAngleList.value.length,
    title: `图层${visualAngleList.value.length + 1}`,
    x,
    y,
    z,
    pitch,
    heading,
    imageUrl: image
  }
  visualAngleList.value.push(visualAngleObject);
}

/**
 * @description 自定义添加视角方法
 */
function visualAngleBtn(currentItem) {
  viewer.camera.flyTo({
    destination: {
      x: currentItem.x,
      y: currentItem.y,
      z: currentItem.z,
    },
    orientation: {
      heading: currentItem.heading,
      pitch: currentItem.pitch,
      roll: 0.0
    },
    duration: 1
  })
}

/**
 * @description 添加Bing影像地图
 */
async function addBingLayer() {
  let imagerProvider = await Cesium.IonImageryProvider.fromAssetId(2);
  const tempLayer = viewer.imageryLayers.addImageryProvider(imagerProvider);
  // tempLayer.show=false;
  // let tempLayer;
  // let imagerProvider = Cesium.IonImageryProvider.fromAssetId(2).then((imagerProvider)=>{
  //   tempLayer = viewer.imageryLayers.addImageryProvider(imagerProvider);
  // });
  return tempLayer;
}

/**
 * @description 添加Bing矢量地图
 */
async function addBingLayerByShiLiang() {
  // let imagerProvider = await Cesium.IonImageryProvider.fromAssetId(4);
  let imagerProvider = await Cesium.IonImageryProvider.fromAssetId(4);
  const tempLayer = viewer.imageryLayers.addImageryProvider(imagerProvider);
  tempLayer.show = false;
  // let tempLayer;
  // let imagerProvider = Cesium.IonImageryProvider.fromAssetId(2).then((imagerProvider)=>{
  //   tempLayer = viewer.imageryLayers.addImageryProvider(imagerProvider);
  //   tempLayer.show = false;
  // });
  return tempLayer;
  // if (baseMapList.value[5].imageryProvider) {
  //   // imageryProviderList[0].alpha = basemapArray[0].transparency / 100;
  //   baseMapList.value[5].imageryProvider.alpha = baseMapList.value[5].transparency / 100;
  // }
  // const tempLayer = viewer.imageryLayers.addImageryProvider(imagerProvider);
  // return tempLayer;
}


/**
 * @description 添加天地图(矢量)底图
 */
function addTianDiTuLayer() {
  const tiandituWMTSUrl = 'http://t{s}.tianditu.gov.cn/vec_w/wmts?tk=7a78bc560f14ba05e24791961deee361';
  const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7'];
  //此API为移除所有图层
  // viewer.imageryLayers.removeAll();
  //我们先把天地图的底图加载出来
  const imageBaseMap = new Cesium.WebMapTileServiceImageryProvider({
    url: tiandituWMTSUrl,
    layer: 'img',
    style: 'default',
    format: 'tiles',
    // tileMatrixSetID: 'GoogleMapsCompatible',
    tileMatrixSetID: 'w',
    tilingScheme: new Cesium.WebMercatorTilingScheme(), // 地理坐标系
    maximumLevel: 18,
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
  });
  // imageryProviderList[1] = viewer.imageryLayers.addImageryProvider(imageBaseMap);
  // //添加
  // addImageryProvider = viewer.imageryLayers.addImageryProvider(imageBaseMap);
  // //设置当前透明度
  // addImageryProvider.alpha = currentTransparency.value;
  //加载注记
  // viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({  //调用矢量地图中文注记服务
  //   url: "http://t{s}.tianditu.com/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=7a78bc560f14ba05e24791961deee361",
  //   subdomains: subdomains,
  //   layer: "tdtAnnoLayer",
  //   style: "default",
  //   format: "image/jpeg",
  //   tileMatrixSetID: "GoogleMapsCompatible",
  // }));
  // imageryProviderList[1].alpha = basemapArray[1].transparency / 100;
  // if (baseMapList.value[1].imageryProvider) {
  //   baseMapList.value[1].imageryProvider.alpha = baseMapList.value[1].transparency / 100;
  // }
  const tempLayers = viewer.imageryLayers.addImageryProvider(imageBaseMap);
  tempLayers.show = false;
  return tempLayers;
}

/**
 * @description 加载天地图影像
 */
function addTianDiTuLayerByYingXiang() {
  const tiandituWMTSUrl = 'http://t{s}.tianditu.gov.cn/vec_w/wmts?tk=8921e4c49ea5a72df8bc5298f40a0616';
  const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7'];
  //此API为移除所有图层
  // viewer.imageryLayers.removeAll();
  //我们先把天地图的底图加载出来
  const imageBaseMap = new Cesium.WebMapTileServiceImageryProvider({
    url: tiandituWMTSUrl,
    layer: 'img',
    style: 'default',
    format: 'tiles',
    // tileMatrixSetID: 'GoogleMapsCompatible',
    tileMatrixSetID: 'w',
    tilingScheme: new Cesium.WebMercatorTilingScheme(), // 地理坐标系
    maximumLevel: 18,
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
  });
  // //添加
  // addImageryProvider = viewer.imageryLayers.addImageryProvider(imageBaseMap);
  // //设置当前透明度
  // addImageryProvider.alpha = currentTransparency.value;
  //加载注记
  // viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({  //调用矢量地图中文注记服务
  //   url: "http://t{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=7a78bc560f14ba05e24791961deee361",
  //   subdomains: subdomains,
  //   layer: "tdtAnnoLayer",
  //   style: "default",
  //   format: "image/jpeg",
  //   tileMatrixSetID: "GoogleMapsCompatible",
  // }));
  // imageryProviderList[4] = viewer.imageryLayers.addImageryProvider(imageBaseMap);
  // imageryProviderList[4].alpha = basemapArray[4].transparency / 100;
  if (baseMapList.value[4].imageryProvider) {
    baseMapList.value[4].imageryProvider.alpha = baseMapList.value[4].transparency / 100;
  }
  const tempLayers = viewer.imageryLayers.addImageryProvider(imageBaseMap);
  tempLayers.show = false;
  return tempLayers;
}


/**
 * @description 添加高德底图
 */
function addGaoDeLayer() {
  //此API为移除所有图层
  // viewer.imageryLayers.removeAll();
  // https://restapi.amap.com/v3/staticmap?location=116.481485,39.990464&zoom=10&size=750*300&markers=mid,,A:116.481485,39.990464&key=68349053d641e76ffff9b70ac68d6866
  const gaoDeImageLayer = new Cesium.UrlTemplateImageryProvider({
    url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
    minimumLevel: 3,
    maximumLevel: 18
  });
  // addImageryProvider = viewer.imageryLayers.addImageryProvider(gaoDeImageLayer);
  // //设置当前透明度
  // addImageryProvider.alpha = currentTransparency.value;
  /** 添加高德地图注记 */
  const gaoDeAnnLayer = new Cesium.UrlTemplateImageryProvider({
    url: "http://webst02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8",
    minimumLevel: 3,
    maximumLevel: 18
  });
  // viewer.imageryLayers.addImageryProvider(gaoDeAnnLayer);
  // imageryProviderList[3] = viewer.imageryLayers.addImageryProvider(gaoDeImageLayer);
  // imageryProviderList[3].alpha = basemapArray[3].transparency / 100;
  if (baseMapList.value[3].imageryProvider) {
    baseMapList.value[3].imageryProvider.alpha = baseMapList.value[3].transparency / 100;
  }
  const tempLayers = viewer.imageryLayers.addImageryProvider(gaoDeImageLayer);
  tempLayers.show = false;
  return tempLayers;
}

/**
 * @description 添加ArcGis在线地图服务
 * 注意：该方法为异步
 */
async function addArcGisLayer() {
  //此API为移除所有图层
  // viewer.imageryLayers.removeAll();
  const arcGisImageLayer = await Cesium.ArcGisMapServerImageryProvider.fromUrl(
    'https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer',
  );
  const tempLayer = viewer.imageryLayers.addImageryProvider(arcGisImageLayer);
  tempLayer.show = false;
  //   .then((arcGisImageLayer)=>{
  //   tempLayer = viewer.imageryLayers.addImageryProvider(arcGisImageLayer);
  //   tempLayer.show = false;
  // },(error)=>{
  //   console.log(error);
  // });
  // addImageryProvider = viewer.imageryLayers.addImageryProvider(arcGisImageLayer);
  // //设置当前透明度
  // addImageryProvider.alpha = currentTransparency.value;
  // imageryProviderList[2] = viewer.imageryLayers.addImageryProvider(arcGisImageLayer);
  // imageryProviderList[2].alpha = basemapArray[2].transparency / 100;
  // if (baseMapList.value[2].imageryProvider) {
  //   baseMapList.value[2].imageryProvider.alpha = baseMapList.value[2].transparency / 100;
  // }
  // viewer.imageryLayers.addImageryProvider(arcGisImageLayer).show = false;
  return tempLayer;
}

/**
 * @description 加载株洲的wms地图服务
 */
function addZhuzhouWmsLayer() {
  const zhuZhouProvider = new Cesium.ImageryLayer(
    new Cesium.WebMapServiceImageryProvider({
      url: "http://192.168.1.137:8080/geoserver/zz_map/wms",
      // layers: "zz_map:0",//调用的服务名称
      layers: "zz_map:株洲市行政区_区县级",//调用的服务名称
      // layers: "zz_map:zz-map",//调用的服务名称
      parameters: {//参数
        transparent: true,//是否透明
        format: "image/png",//这里尽量不要去使用jpeg
      },
    })
  );
  viewer.camera.flyTo({
    duration: 1,
    // destination: Cartesian3.fromDegrees(113.1744, 27.8416, 4000.0),
    destination: Cartesian3.fromDegrees(114.0113, 27.8303, 4000.0),
    // orientation: {
    //   heading: Cesium.Math.toRadians(90.0),  // 方位角（水平旋转角度）
    //   pitch: Cesium.Math.toRadians(-45.0),   // 俯仰角（相机上下旋转）
    //   roll: 0.0                             // 滚动角（相机左右倾斜）
    // },
  });
  if (baseMapList.value[6].imageryProvider) {
    baseMapList.value[6].imageryProvider.alpha = baseMapList.value[6].transparency / 100;
  }
  viewer.imageryLayers.add(zhuZhouProvider)
  zhuZhouProvider.show = false
  return zhuZhouProvider;
}


/**
 * @description 加载江苏矢量图层
 */
async function addJinagSuByShiLiangLayer() {
  //坐标系转化
  const _layerInfo = {
    "id": "china4490",
    // "zoomoffset": 1,
    // "layerUrl": "https://localhost:6443/arcgis/rest/services/CGCS2000/China_xzq/MapServer/tile/{level}/level/{row}/${col}"
    "layerUrl": "https://jiangsu.tianditu.gov.cn/mapjs2/rest/services/MapJS/js_sldt_latest/MapServer/tile/{TileMatrix}/{TileRow}/{TileCol}"
  };
  const jiangSuProvider = new Cesium.WebMapTileServiceImageryProvider({
    url: _layerInfo.layerUrl,
    layer: _layerInfo.id,
    tilingScheme: new Cesium.GeographicTilingScheme(),
    tileMatrixSetID: "TDTMapsCompatible",
    //注意，江苏矢量图层不是从0开始的，而是从1开始
    tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"],
    style: ""
  });
  viewer.camera.flyTo({
    duration: 1,
    destination: Cartesian3.fromDegrees(119.8974, 32.0188, 6000.0),
    // orientation: {
    //   heading: Cesium.Math.toRadians(90.0),  // 方位角（水平旋转角度）
    //   pitch: Cesium.Math.toRadians(-45.0),   // 俯仰角（相机上下旋转）
    //   roll: 0.0                             // 滚动角（相机左右倾斜）
    // },
  });
  const tempLayer = viewer.imageryLayers.addImageryProvider(jiangSuProvider);
  tempLayer.show = false;
  baseMapList.value[7].imageryProvider = tempLayer;
  return tempLayer;
}

/**
 * @description 加载江苏中学Layer
 */
async function addJinagSuByZhongXueLayer() {
  //坐标系转化
  const _layerInfo = {
    "id": "china4490",
    // "zoomoffset": 1,
    // "layerUrl": "https://localhost:6443/arcgis/rest/services/CGCS2000/China_xzq/MapServer/tile/{level}/level/{row}/${col}"
    "layerUrl": "https://jiangsu.tianditu.gov.cn/thematicmap/rest/services/ZTFW/zhongxue/MapServer/tile/{TileMatrix}/{TileRow}/{TileCol}"
  };
  const jiangSuProvider = new Cesium.WebMapTileServiceImageryProvider({
    url: _layerInfo.layerUrl,
    layer: _layerInfo.id,
    tilingScheme: new Cesium.GeographicTilingScheme(),
    tileMatrixSetID: "TDTMapsCompatible",
    tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"],
    style: ""
  });
  viewer.camera.flyTo({
    duration: 1,
    destination: Cartesian3.fromDegrees(119.8974, 32.0188, 6000.0),
    // orientation: {
    //   heading: Cesium.Math.toRadians(90.0),  // 方位角（水平旋转角度）
    //   pitch: Cesium.Math.toRadians(-45.0),   // 俯仰角（相机上下旋转）
    //   roll: 0.0                             // 滚动角（相机左右倾斜）
    // },
  });
  const tempLayer = viewer.imageryLayers.addImageryProvider(jiangSuProvider);
  tempLayer.show = false;
  baseMapList.value[8].imageryProvider = tempLayer;
  return tempLayer;
}

/**
 * @description 加载江苏医院
 * @returns {Promise<ImageryLayer>}
 */
async function addJinagSuByYiYuanLayer() {
  //坐标系转化
  const _layerInfo = {
    "id": "china4490",
    // "zoomoffset": 1,
    // "layerUrl": "https://localhost:6443/arcgis/rest/services/CGCS2000/China_xzq/MapServer/tile/{level}/level/{row}/${col}"
    "layerUrl": "https://jiangsu.tianditu.gov.cn/thematicmap/rest/services/ZTFW/zongheyy1/MapServer/tile/{TileMatrix}/{TileRow}/{TileCol}"
  };
  const jiangSuProvider = new Cesium.WebMapTileServiceImageryProvider({
    url: _layerInfo.layerUrl,
    layer: _layerInfo.id,
    tilingScheme: new Cesium.GeographicTilingScheme(),
    tileMatrixSetID: "TDTMapsCompatible",
    tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"],
    style: ""
  });
  viewer.camera.flyTo({
    duration: 1,
    destination: Cartesian3.fromDegrees(119.8974, 32.0188, 6000.0),
    // orientation: {
    //   heading: Cesium.Math.toRadians(90.0),  // 方位角（水平旋转角度）
    //   pitch: Cesium.Math.toRadians(-45.0),   // 俯仰角（相机上下旋转）
    //   roll: 0.0                             // 滚动角（相机左右倾斜）
    // },
  });
  const tempLayer = viewer.imageryLayers.addImageryProvider(jiangSuProvider);
  tempLayer.show = false;
  baseMapList.value[9].imageryProvider = tempLayer;
  return tempLayer;
}

/**
 * @description 加载江苏注记
 * @returns {Promise<ImageryLayer>}
 */
async function addJinagSuByZhuJiLayer() {
  //坐标系转化
  const _layerInfo = {
    "id": "china4490",
    // "zoomoffset": 1,
    // "layerUrl": "https://localhost:6443/arcgis/rest/services/CGCS2000/China_xzq/MapServer/tile/{level}/level/{row}/${col}"
    "layerUrl": "https://jiangsu.tianditu.gov.cn/mapjs2/rest/services/MapJS/js_slzj_latest/MapServer/tile/{TileMatrix}/{TileRow}/{TileCol}"
  };
  const jiangSuProvider = new Cesium.WebMapTileServiceImageryProvider({
    url: _layerInfo.layerUrl,
    layer: _layerInfo.id,
    tilingScheme: new Cesium.GeographicTilingScheme(),
    tileMatrixSetID: "TDTMapsCompatible",
    tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"],
    style: ""
  });
  viewer.camera.flyTo({
    duration: 1,
    destination: Cartesian3.fromDegrees(119.8974, 32.0188, 6000.0),
    // orientation: {
    //   heading: Cesium.Math.toRadians(90.0),  // 方位角（水平旋转角度）
    //   pitch: Cesium.Math.toRadians(-45.0),   // 俯仰角（相机上下旋转）
    //   roll: 0.0                             // 滚动角（相机左右倾斜）
    // },
  });
  const tempLayer = viewer.imageryLayers.addImageryProvider(jiangSuProvider);
  tempLayer.show = false;
  baseMapList.value[10].imageryProvider = tempLayer;
  return tempLayer;
}

/**
 * @description 添加点缓冲区
 */
function pointDialogFormSubmitBtn() {
  initPointBuffer(viewer, publicCesiumHandler, pointDialogForm.range);
  // viewer.scene.camera.setView({
  //   destination: Cesium.Cartesian3.fromDegrees(114.40086, 30.51888, 2000),
  // });
  pointDialogFormVisible.value = false;
}

/**
 * @description 添加线缓冲区
 */
function addPolylineBuffer() {
  //添加
  initPolylineBuffer(viewer, publicCesiumHandler, pointLineDialogForm.range);
  pointLineDialogFormVisible.value = false;
  //更新
  // updatePolylineBuffer(viewer, pointLineDialogForm.range);
  // viewer.scene.camera.setView({
  //   destination: Cesium.Cartesian3.fromDegrees(114.40086, 30.51888, 2000),
  // });
}

/**
 * @description 添加面缓冲区
 */
function addPolygonBuffer() {
  // DrawPolygon
  const drawPolygon = new DrawPolygon({
    viewer,
    Cesium,
    cesiumHandler: publicCesiumHandler,
    callback: initPolygonBuffer,
    range: surfaceDialogForm.range
  });
  drawPolygon.startCreate();
  // updatePolygonBuffer(viewer, surfaceDialogForm.range);
  surfaceDialogFormVisible.value = false;
  // initPolygonBuffer(viewer,pointList);
  // viewer.scene.camera.setView({
  //   destination: Cesium.Cartesian3.fromDegrees(114.40086, 30.51888, 2000),
  // });
}

/**
 * @description 地形开挖
 */
function terrainExcavationFun() {
  //实例化TerrainCutting类
  // const terrainCutting = new TerrainCutting(viewer);
  //开始挖掘
  // terrainCutting.create();
  // const excavationTool = new initExcavationTool(viewer, {
  //   height: 100,
  //   splitNum: 1000,
  //   bottomImg: import('./assets/image/popup_icon.png'),
  //   wallImg: import('./assets/image/popup_icon.png'),
  // });

  const terrainClipPlanObj = new TerrainExcavation(viewer, {
    height: 300,
    splitNum: 1000,
    bottomImg: import("./assets/image/terrain-clip-bottom.jpeg"),
    wallImg: import("./assets/image/terrain-clip-aside.jpeg"),
  });
  terrainClipPlanObj.startCreate();

  // const terrainExcavation2=new TerrainExcavation2(viewer);
  //
  // viewer.scene.camera.setView({
  //   destination: Cesium.Cartesian3.fromDegrees(-115.0, 37.0, 1000),
  // });

  // isTerrainExcavation.value = !isTerrainExcavation.value;
  // const terrainExcavation = new TerrainExcavation(viewer, publicCesiumHandler);
  // if (isTerrainExcavation.value) {
  //   viewer.scene.camera.setView({
  //     destination: Cesium.Cartesian3.fromDegrees(114.39564, 30.52214, 2000),
  //   });
  //   terrainExcavation.startEvent();
  //   terrainExcavation.rightDownTexture();
  // } else {
  //   terrainExcavation.closeEvent();
  // }

  // const terrainExcavation= new TerrainClipPlan(viewer,{
  //   height:200,
  //   splitNum: 1000,
  //   bottomImg: '../assets/image/fjt.jpg',
  //   wallImg: '../assets/image/fjt.jpg'
  // });
  //
  // terrainExcavation.updateData([
  //   [114.3940, 30.5220],
  //   [114.3970, 30.5220],
  //   [114.3980, 30.5240],
  //   [114.3960, 30.5250],
  //   [114.3940, 30.5220],
  // ]);
}

/**
 * @description 弹框关闭按钮
 */
function dialogFormCloseBtn() {
  dialogFormVisible.value = false;
  //恢复默认值
  form.range = 30;
}

/**
 * @description 弹框确定按钮
 */
function dialogFormSubmitBtn() {
  // 清除之前的缓冲区
  viewer.entities.removeAll();
  console.log(1680, form.range);
  updatePolygonBuffer(viewer, form.range);
  dialogFormVisible.value = false;
}

/**
 * @description 清空缓冲区
 */
function clearBuffer() {
  clearAllEntitiesList(viewer);
  const drawPolygon = new DrawPolygon({
    viewer,
    Cesium,
    cesiumHandler: publicCesiumHandler,
    range: surfaceDialogForm.range
  });
  drawPolygon.clear();
}


</script>
<style scoped>
.app-box {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.map-box {
  width: 100%;
  height: 100%;
}

.menu-box {
  position: absolute;
  right: 0;
  top: 0;
  z-index: 10;
}

.popup-box {
  position: absolute;
  background: #ffffff;
  color: #000000;
  z-index: 10;
  top: 0;
  left: 0;
  width: 200px;
}

.popup-message-content {
  display: flex;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100% 100%;
  padding: 5px;
}

.popup-content-left {
  width: 150px;
}

.popup-left-top {
  display: flex;
  font-size: 13px;
  color: #0d7af9;
}

.popup-left-top img {
  width: 50px;
  height: 50px;
}

.popup-left-top-content div {
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.popup-left-image {
  display: block;
  margin: 0 auto;
  width: 120px;
  height: 100px;
}

.popup-box-ul {
  color: #ffffff;
}

.popup-box-ul li {
  color: #ffffff;
}

</style>
